const { invoke } = window.__TAURI__.core;
const { listen } = window.__TAURI__.event;

window.addEventListener("DOMContentLoaded", () => {
  const playrwright_result_ul = document.querySelector("#playwright-result > ul");
  const playrwright_result = document.querySelector("#playwright-result");

  listen("data-task-message", (event) => {
    console.log('Received data from backend:', event.payload);
    if (event.payload.status !== "stop") {
      const li = document.createElement("li");
      li.className = `list-item`;
      li.innerHTML = `
        <span class="text-base font-medium text-gray-800">${event.payload.data}</span>
        <span class="text-sm font-semibold ${event.payload.status === "success" ? "text-green-600" : "text-yellow-600"
        }">
          ${event.payload.status}
        </span>
      `
      playrwright_result_ul.appendChild(li);
      playrwright_result.scrollTop = playrwright_result.scrollHeight;
    } else {
      console.log("Playwright task finished");
      // 触发自定义事件
      window.dispatchEvent(new CustomEvent('playwright-finished'));
    }
  });
});

// 添加任务
async function run_playwright() {
  // 触发自定义事件
  window.dispatchEvent(new CustomEvent('playwright-started'));
  await invoke("run_playwright", { urlList: ["https://www.baidu.com"] });
}

async function clear_playwright_result() {
  const playrwright_result_ul = document.querySelector("#playwright-result > ul");
  playrwright_result_ul.innerText = "";
}
